import { useState, useEffect } from 'react';
import { message } from 'antd';
import { PlatformTenantDto, PlatformTenantQuery } from '../../types/platform';
import { tenantApi } from '../../services/platform/api/tenantApi';

// 租户查询参数类型
interface TenantQueryParams {
  page?: number;
  size?: number;
  search?: string;
  status?: string;
}

// 租户表单数据类型
interface TenantForm {
  name: string;
  code: string;
  domain?: string;
  industry?: string;
  description?: string;
  contactName: string;
  contactEmail: string;
  contactPhone?: string;
  planType: 'basic' | 'pro' | 'enterprise';
  maxUsers: number;
}

// 租户列表管理hook
export const useTenants = (params?: TenantQueryParams) => {
  const [tenants, setTenants] = useState<PlatformTenantDto[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchTenants = async () => {
    try {
      setLoading(true);
      const query: PlatformTenantQuery = {
        current: pagination.current,
        size: pagination.pageSize,
        name: params?.search,
        status: params?.status === 'all' ? undefined : 
                params?.status === 'active' ? 1 :
                params?.status === 'suspended' ? 3 :
                params?.status === 'expired' ? 4 : undefined,
      };
      
      const response = await tenantApi.getPlatformTenants(query);
      console.log(response)
      
      // 响应拦截器已经返回了 data.data，所以直接访问属性
      // 使用类型断言来处理响应数据
      const responseData = response as any;
      if (responseData && typeof responseData === 'object') {
        setTenants(responseData.records || []);
        setPagination(prev => ({
          ...prev,
          total: responseData.total || 0,
        }));
      } else {
        console.warn('响应数据格式异常:', responseData);
        setTenants([]);
        setPagination(prev => ({ ...prev, total: 0 }));
      }
    } catch (error) {
      console.error('获取租户列表失败:', error);
      message.error('获取租户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTenants();
  }, [pagination.current, pagination.pageSize, params?.search, params?.status]);

  const updatePagination = (page: number, size?: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: size || prev.pageSize,
    }));
  };

  return {
    tenants,
    loading,
    pagination,
    updatePagination,
    refresh: fetchTenants,
  };
};

// 租户详情管理hook
export const useTenant = (id?: string) => {
  const [tenant, setTenant] = useState<PlatformTenantDto | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchTenant = async (tenantId: string) => {
    try {
      setLoading(true);
      const response = await tenantApi.getPlatformTenant(tenantId);
      setTenant(response.data);
    } catch (error) {
      console.error('获取租户详情失败:', error);
      message.error('获取租户详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchTenant(id);
    }
  }, [id]);

  return {
    tenant,
    loading,
    refresh: () => id && fetchTenant(id),
  };
};

// 租户操作管理hook
export const useTenantActions = () => {
  const [loading, setLoading] = useState(false);

  const createTenant = async (data: TenantForm) => {
    try {
      setLoading(true);
      const tenantData: Partial<PlatformTenantDto> = {
        name: data.name,
        code: data.code,
        domain: data.domain,
        description: data.description,
        contactName: data.contactName,
        contactEmail: data.contactEmail,
        contactPhone: data.contactPhone,
        planType: data.planType,
        maxUsers: data.maxUsers,
        status: 1, // 默认正常状态
      };

      const result = await tenantApi.createPlatformTenant(tenantData);
      message.success('租户创建成功');
      return result;
    } catch (error: any) {
      message.error(error.message || '租户创建失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateTenant = async (id: string, data: Partial<TenantForm>) => {
    try {
      setLoading(true);
      const tenantData: Partial<PlatformTenantDto> = {
        name: data.name,
        code: data.code,
        domain: data.domain,
        description: data.description,
        contactName: data.contactName,
        contactEmail: data.contactEmail,
        contactPhone: data.contactPhone,
        planType: data.planType,
        maxUsers: data.maxUsers,
      };

      const result = await tenantApi.updatePlatformTenant(id, tenantData);
      message.success('租户更新成功');
      return result;
    } catch (error: any) {
      message.error(error.message || '租户更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteTenant = async (id: string) => {
    try {
      setLoading(true);
      await tenantApi.deletePlatformTenant(id);
      message.success('租户删除成功');
    } catch (error: any) {
      message.error(error.message || '租户删除失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const toggleTenantStatus = async (id: string, status: 'active' | 'suspended') => {
    try {
      setLoading(true);
      if (status === 'active') {
        await tenantApi.activatePlatformTenant(id);
        message.success('租户激活成功');
      } else {
        await tenantApi.suspendPlatformTenant(id);
        message.success('租户暂停成功');
      }
    } catch (error: any) {
      message.error(error.message || '状态切换失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const extendTenantExpiry = async (id: string, months: number) => {
    try {
      setLoading(true);
      await tenantApi.extendPlatformTenantExpiry(id, months);
      message.success(`租户有效期延长${months}个月成功`);
    } catch (error: any) {
      message.error(error.message || '有效期延长失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const upgradeTenantPlan = async (id: string, planType: string, maxUsers: number) => {
    try {
      setLoading(true);
      await tenantApi.upgradePlatformTenantPlan(id, planType, maxUsers);
      message.success('租户套餐升级成功');
    } catch (error: any) {
      message.error(error.message || '套餐升级失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    createTenant,
    updateTenant,
    deleteTenant,
    toggleTenantStatus,
    extendTenantExpiry,
    upgradeTenantPlan,
  };
};